#include "serial_C++.hpp"
#include <unordered_map>
int SerialProtocolHandler::receive_thread_ms = 1;
int SerialProtocolHandler::process_thread_ms = 1;
send_data1_t user_send_data1;
send_data2_t user_send_data2;
static const std::unordered_map<int, speed_t> baud_rate_mapping = {
    {2400, B2400},
    {4800, B4800},
    {9600, B9600},
    {19200, B19200},
    {38400, B38400},
    {57600, B57600},
    {115200, B115200},
    {230400, B230400},
    {460800, B460800},
    {500000, B500000},
    {576000, B576000},
    {921600, B921600},
    {1000000, B1000000},
    {1152000, B1152000},
    {1500000, B1500000},
    {2000000, B2000000},
    {2500000, B2500000},
    {3000000, B3000000},
    {3500000, B3500000},
    {4000000, B4000000}
};
 

void Receive_Data_C::data_arrange(const char* data) {
    now_time = std::chrono::steady_clock::now();
    duration = std::chrono::duration<float>(this->now_time - this->start_time);
    std::memcpy(&this->dart_status, data, sizeof(float));
    std::memcpy(&this->pitch_angle, data + 4, sizeof(float));
    std::memcpy(&this->yaw_angle, data + 8, sizeof(float));
    std::memcpy(&this->roll_angle, data + 12, sizeof(float));
    std::memcpy(&this->temperature, data + 16, sizeof(float));
    std::memcpy(&this->delta_x, data + 20, sizeof(float));
    std::memcpy(&this->delta_y, data + 24, sizeof(float));
    std::memcpy(&this->delta_z, data + 28, sizeof(float));
    std::memcpy(&this->a_x, data + 32, sizeof(float));
    std::memcpy(&this->a_y, data + 36, sizeof(float));
    std::memcpy(&this->a_z, data + 40, sizeof(float));
    std::memcpy(&this->omega_x, data + 44, sizeof(float));
    std::memcpy(&this->omega_y, data + 48, sizeof(float));
    std::memcpy(&this->omega_z, data + 52, sizeof(float));
    std::memcpy(&this->vdd_voltage, data + 56, sizeof(float));
    std::memcpy(&this->vbx, data + 60, sizeof(float));
    std::memcpy(&this->vby, data + 64, sizeof(float));
    std::memcpy(&this->vbz, data + 68, sizeof(float));
    std::memcpy(&this->alpha, data + 72, sizeof(float));
    std::memcpy(&this->beta, data + 76, sizeof(float));
}
void Receive_Data_C::my_print()
{
    std::cout << "######################################" << std::endl;
    std::cout << "time: "<< duration.count() << std::endl;
    std::cout << "dart_status: " << dart_status << " pitch_angle: " << pitch_angle << " yaw_angle: " << yaw_angle << " roll_angle: " << roll_angle << " temperature: " << temperature << std::endl;
    std::cout << "delta_x: " << delta_x << " delta_y: " << delta_y << " delta_z: " << delta_z << std::endl;
    std::cout << "a_x: " << a_x << " a_y: " << a_y << " a_z: " << a_z << std::endl;
    std::cout << "omega_x: " << omega_x << " omega_y: " << omega_y << " omega_z: " << omega_z << std::endl;
    std::cout << "vdd_voltage: " << vdd_voltage << std::endl;
    std::cout << "vbx: " << vbx << " vby: " << vby << " vbz: " << vbz << std::endl;
    std::cout << "alpha: " << alpha << " beta: " << beta << std::endl;
    std::cout << "######################################" << std::endl;
}

void Receive_Data_C::Data_Storage()
{
    if(file_output.is_open())
    {
        file_output << duration.count() << " " << dart_status << " " << pitch_angle << " " << yaw_angle << " " << roll_angle << " " << temperature << " " 
        << delta_x << " " << delta_y << " " << delta_z << " " << a_x << " " << a_y << " " << a_z << " "
        << omega_x << " " << omega_y << " " << omega_z << " " << vdd_voltage << " "
        << vbx << " " << vby << " " << vbz << " " << alpha << " " << beta << std::endl;

        if (file_output.fail()) {
            std::cerr << "Failed to write to file" << std::endl;
        }
    }
    else std::cout << "StorageFunction file not open" << std::endl;
}

SerialProtocolHandler::SerialProtocolHandler(const std::string& port, int baudrate, int data_bits, int stop_bits, char parity, 
    std::function<void(const std::vector<uint8_t>&)> callback)
: port(port), baudrate(baudrate), data_bits(data_bits), stop_bits(stop_bits), parity(parity), callback(callback), fd(-1), _running(false) {
    configure_serial_port();
}

SerialProtocolHandler::~SerialProtocolHandler()
{
    stop();
}
void SerialProtocolHandler::start()
{
    _running = true;
    receiver_thread = std::thread(&SerialProtocolHandler::_receive_thread, this);
    processor_thread = std::thread(&SerialProtocolHandler::_process_thread, this);
}
void SerialProtocolHandler::start_cv()
{
    _running = true;
    receiver_thread = std::thread(&SerialProtocolHandler::_receive_thread, this);
    processor_thread = std::thread(&SerialProtocolHandler::_process_thread_cv, this);
}
void SerialProtocolHandler::stop()
{
    _running = false;
    if (receiver_thread.joinable()) receiver_thread.join();
    if (processor_thread.joinable()) processor_thread.join();
    if (fd != -1) {
        close(fd);
        fd = -1;
    }
}
void SerialProtocolHandler::send(const std::vector<uint8_t>& data) {
    if (fd == -1) throw std::runtime_error("Serial port not open");
    //可能有开销
    std::vector<uint8_t> message = { MYPACK_FRAMEHEADER_SOF1, MYPACK_FRAMEHEADER_SOF2, static_cast<uint8_t>(data.size()) };
    message.insert(message.end(), data.begin(), data.end());
    message.push_back(0); // CRC placeholder
    message.push_back(0); // CRC placeholder

    uint16_t crc = _get_crc16(message.data(), message.size() - 2, 0xFFFF);
    message[message.size() - 2] = crc & 0xFF;
    message[message.size() - 1] = (crc >> 8) & 0xFF;

    if (write(fd, message.data(), message.size()) == -1) {
        throw std::runtime_error("Serial write error");
    }
}

void SerialProtocolHandler::send(const void* message,const uint8_t message_size)
{
    if (fd == -1) throw std::runtime_error("Serial port not open");
    uint8_t message_send[message_size + 5];
    message_send[0] = MYPACK_FRAMEHEADER_SOF1;
    message_send[1] = MYPACK_FRAMEHEADER_SOF2;
    message_send[2] = message_size;
    memcpy(message_send + 3,message,message_size);
    _append_CRC16_Check_Sum(message_send,message_size + 5);
  //   message_send[message_size] = '\r';
  //   message_send[message_size + 1] = '\n';
    //write(fd, message_send, message_size + 5);
    //int res = write(fd, message_send, message_size + 5);
    // if (res) {
    //     std::cout<<"error_code: "<<res<<std::endl;
    //     throw std::runtime_error("Serial write error");
    // }
    if (write(fd, message_send, sizeof(message_send)) == -1) {
        throw std::runtime_error("Serial write error");
    }
}
void SerialProtocolHandler::configure_serial_port() {
    fd = open(port.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (fd == -1) throw std::runtime_error("Unable to open serial port");

    struct termios options;
    
    // 获取当前串口的设置
    if (tcgetattr(fd, &options) != 0) {
        std::cerr << "Error getting serial port attributes" << std::endl;
        return;
    }

    options.c_iflag &= ~(ICRNL | INLCR | IGNCR);//ICRNL 映射输入上的 CR 到 NL;INLCR 将 NL 映射到输入上的 CR;IGNCR 忽略回车符

    //需要添加波特率映射表
    try {
        speed_t baud = baud_rate_mapping.at(baudrate);
        cfsetispeed(&options, baud);
        cfsetospeed(&options, baud);
    } catch (const std::out_of_range& e) {
        throw std::invalid_argument("Invalid baud rate");
    }
    // cfsetispeed(&options, baudrate);
    // cfsetospeed(&options, baudrate);

    options.c_cflag &= ~CSIZE;
    switch (data_bits) {
        case 5: options.c_cflag |= CS5; break;
        case 6: options.c_cflag |= CS6; break;
        case 7: options.c_cflag |= CS7; break;
        case 8: options.c_cflag |= CS8; break;
        default: throw std::invalid_argument("Invalid data bits");
    }

    if (stop_bits == 1) {
        options.c_cflag &= ~CSTOPB;
    } else if (stop_bits == 2) {
        options.c_cflag |= CSTOPB;
    } else {
        throw std::invalid_argument("Invalid stop bits");
    }

    if (parity == 'N') {
        options.c_cflag &= ~PARENB;  // 无校验
        options.c_iflag &= ~INPCK;   // 不启用输入校验
    } else if (parity == 'O') {
        options.c_cflag |= PARENB;   // 开启校验
        options.c_cflag |= PARODD;   // 奇校验
        options.c_iflag |= INPCK;    // 启用输入校验
    } else if (parity == 'E') {
        options.c_cflag |= PARENB;   // 开启校验
        options.c_cflag &= ~PARODD;  // 偶校验
        options.c_iflag |= INPCK;    // 启用输入校验
    }else {
        throw std::invalid_argument("Invalid parity");
    }

    // 使能串口配置并关闭硬件流控制
    options.c_cflag |= (CLOCAL | CREAD);  // 启用接收并忽略调制解调器控制线
    options.c_cflag &= ~CRTSCTS;          // 禁用硬件流控制
    options.c_iflag &= ~(IXON | IXOFF | IXANY);// 禁用软件流控制
    //options.c_iflag |= IXON | IXOFF | IXANY;
    //软件流控制:options.c_iflag |= IXON | IXOFF | IXANY

    // 设置串口为原始模式
    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    options.c_oflag &= ~OPOST;

    // 设置数据传输时的字符大小，接收超时等(no blocked模式无意义)
    options.c_cc[VMIN] = 0;    // 1,至少读取 1 字节数据
    options.c_cc[VTIME] = 0;   // 5,超时 0.5 秒

    tcsetattr(fd, TCSANOW, &options);
    tcflush(fd, TCIFLUSH);
}

void SerialProtocolHandler::_receive_thread()
{
    while (_running) {
        size_t len = read(fd, data, BUFFER_SIZE);
        if (len > 0) {
            for (size_t i = 0; i < len; ++i) {
                _unpack_byte(data[i]);
            }
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(receive_thread_ms));
        //std::cout << "r_running" << std::endl;
    }
    //std::cout << "rr_running" << std::endl;
    return;
}
void SerialProtocolHandler::_unpack_byte(uint8_t byte)
{
    RXBuffer& rx = unpacker.RX_Buffer;
    auto& status = unpacker.PackRX_Status;

    if (status == PACKRX_STATUS_ENUM::MyPack_Frame_SOF) {
        if (byte == MYPACK_FRAMEHEADER_SOF1 && unpacker.SOF_count == 0) {
            rx.all_data[0] = byte;
            unpacker.SOF_count = 1;
        } else if (byte == MYPACK_FRAMEHEADER_SOF2 && unpacker.SOF_count == 1) {
            rx.all_data[1] = byte;
            unpacker.SOF_count = 0;
            rx.length = 0;
            status = PACKRX_STATUS_ENUM::MyPack_Frame_DataLength;
        } else {
            unpacker.SOF_count = 0;
        }
    } else if (status == PACKRX_STATUS_ENUM::MyPack_Frame_DataLength) {
        rx.length = byte;
        rx.all_data[2] = byte;
        status = PACKRX_STATUS_ENUM::MyPack_Frame_DATA;
        unpacker.DataLenth_count = 0;
    } else if (status == PACKRX_STATUS_ENUM::MyPack_Frame_DATA) {
        if (unpacker.DataLenth_count < BUFFER_SIZE) {
            rx.buffer[unpacker.DataLenth_count] = byte;
            rx.all_data[3 + unpacker.DataLenth_count] = byte;
            unpacker.DataLenth_count++;
            if (unpacker.DataLenth_count >= rx.length) {
                unpacker.CRC16_count = 0;
                status = PACKRX_STATUS_ENUM::MyPack_Frame_CRC16;
            }
        }
    } else if (status == PACKRX_STATUS_ENUM::MyPack_Frame_CRC16) {
        if (unpacker.CRC16_count == 0) {
            rx.CRC_data = byte;
            rx.all_data[3 + rx.length] = byte;
            unpacker.CRC16_count = 1;
        } else if (unpacker.CRC16_count == 1) {
            rx.all_data[4 + rx.length] = byte;
            rx.CRC_data |= byte << 8;
            status = PACKRX_STATUS_ENUM::MyPack_Frame_SOF;
            if (_verify_crc(rx.all_data.data(), rx.length + 5)) {
                std::lock_guard<std::mutex> lock(mtx);
                receive_queue.push(std::vector<uint8_t>(rx.buffer.begin(), rx.buffer.begin() + rx.length));
                cv.notify_all();
            }
        }
    }
}

bool SerialProtocolHandler::_verify_crc(const uint8_t* data, size_t length) {
    if (length <= 2) return false;
    uint16_t wExpected = _get_crc16(data, length - 2, 0xFFFF);
    return (wExpected & 0xFF) == data[length - 2] && ((wExpected >> 8) & 0xFF) == data[length - 1];
}


uint16_t SerialProtocolHandler::_get_crc16(const uint8_t* data, size_t length, uint16_t crc_init) {
    static const uint16_t wCRC_Table[256] = {
        0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
        0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
        0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
        0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
        0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
        0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
        0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
        0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
        0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
        0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
        0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
        0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
        0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
        0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
        0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
        0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
        0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
        0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
        0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
        0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
        0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
        0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
        0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
        0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
        0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
        0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
        0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
        0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
        0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
        0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
        0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
        0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
    };

    uint16_t crc = crc_init;
    for (size_t i = 0; i < length; ++i) {
        crc = (crc >> 8) ^ wCRC_Table[(crc ^ data[i]) & 0xFF];
    }
    return crc;
}

void SerialProtocolHandler::_append_CRC16_Check_Sum(uint8_t * pchMessage,uint32_t dwLength)
{
    uint16_t wCRC = 0;
    if ((pchMessage == NULL) || (dwLength <= 2))
    {
        return;
    }
    wCRC = _get_crc16 ( (uint8_t *)pchMessage, dwLength-2, 0xFFFF);
    pchMessage[dwLength-2] = (uint8_t)(wCRC & 0x00ff);
    pchMessage[dwLength-1] = (uint8_t)((wCRC >> 8)& 0x00ff);
}

void SerialProtocolHandler::_process_thread() {
    while (_running) {
        std::vector<uint8_t> data;
        {
            std::lock_guard<std::mutex> lock(mtx);
            if (!receive_queue.empty()) {
                data = receive_queue.front();
                receive_queue.pop();
            }
        }
        if (!data.empty() && callback) {
            callback(data);
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(process_thread_ms));
    }
}

void SerialProtocolHandler::_process_thread_cv()
{
    while(_running){
        std::vector<uint8_t> data;
        std::unique_lock<std::mutex> lock(mtx);
        //cv.wait(lock,[this](){ return !this->receive_queue.empty();});
        // 等待队列非空或_ running为false
        cv.wait_for(lock, std::chrono::milliseconds(1000), [this](){ return !_running || !this->receive_queue.empty(); });
            // 如果有数据或者 _running 为 false，继续处理
        if(!_running) {
            break;
        }
        if(!receive_queue.empty()){
            data = receive_queue.front();
            receive_queue.pop();
            if(callback)
            {
                callback(data);
            }
        }
        lock.unlock();


        //std::cout << "p_running" << std::endl;
    }
    //std::cout << "pp_running" << std::endl;
    return;
}

